package com.db.mongo;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.bson.Document;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

public class MongoDocument {
	
	private static final String ip = "localhost";
	private static final int port = 27017;
	private static final String db = "test";
	

	public static void main(String args[]) {
		String table = "user";
		createCollection(table);
		insertDocument(table);
		findDocument(table);
	}


	private static void findDocument(String table) {
		MongoDatabase mongoDatabase = MongoDBFactory.create(ip, port, db);
		MongoCollection<Document> collection = mongoDatabase.getCollection(table);
		// 获得所有行并打印
		collection.find().forEach((Document d) -> System.out.println(d));
	}


	private static void insertDocument(String table) {
		MongoDatabase mongoDatabase = MongoDBFactory.create(ip, port, db);
		// Document相当于行
		MongoCollection<Document> collection = mongoDatabase.getCollection(table);
		System.out.println("document before, size=" + collection.count());
		/**
		 * 插入文档 1. 创建文档 org.bson.Document 参数为key-value的格式 2.
		 * 创建文档集合List<Document> 3. 将文档集合插入数据库集合中
		 * mongoCollection.insertMany(List<Document>) 插入单个文档可以用
		 * mongoCollection.insertOne(Document)
		 */
		Document document = new Document("uid", UUID.randomUUID())
				.append("name", "@斯巴达@")
				.append("age", 22);
		List<Document> documents = new ArrayList<Document>();
		documents.add(document);
		collection.insertMany(documents);
		System.out.println("document after, size=" + collection.count());
	}


	private static void createCollection(String table) {
		MongoDatabase mongoDatabase = MongoDBFactory.create(ip, port, db);
		// 判断Collection是否已存在
		boolean has = false;
		for (MongoCursor<String> iterator = mongoDatabase.listCollectionNames().iterator(); iterator.hasNext();) {
			String name = iterator.next();
			if (table.equals(name)) {
				has = true;
				break;
			}
		}
		if (!has) {
			// 创建Collection,即表的概念
			mongoDatabase.createCollection(table);
			System.out.println("create success Collection:" + table);
		}
	}
}